const Koa = require('koa')
const app = new Koa()
const jwt = require('koa-jwt')
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const Router = require('koa-router')
const users = require('./routes/users')
const echarts = require('./routes/echarts')
const menu = require('./routes/menu')
const role = require('./routes/role')
const dept = require('./routes/dept')
const leave = require('./routes/leave')
const uploads = require('./routes/uploads')
const { default: session } = require('koa-session') // session


// session 配置
app.keys = ['some secret hurr'];
const CONFIG = {
  key: 'koa.sess', /** (string) cookie key (default is koa.sess) */
  /** (number || 'session') maxAge in ms (default is 1 days) */
  /** 'session' will result in a cookie that expires when session/browser is closed */
  /** Warning: If a session cookie is stolen, this cookie will never expire */
  maxAge: 86400000,
  autoCommit: true, /** (boolean) automatically commit headers (default true) */
  overwrite: true, /** (boolean) can overwrite or not (default true) */
  httpOnly: true, /** (boolean) httpOnly or not (default true) */
  signed: true, /** (boolean) signed or not (default true) */
  rolling: false, /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. (default is false) */
  renew: false, /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/
  secure: false, /** (boolean) secure cookie*/
  sameSite: 'lax', /** (string) session cookie sameSite options (default null, don't set it) */
};
app.use(session(CONFIG, app));

// error handler
onerror(app)
require('./config/db')

// middlewares
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
const router = new Router()
router.prefix('/api')
app.use(jwt({ secret: 'lee' }).unless({ path: [/^\/api\/users\/login/, /^\/api\/users\/captcha/] }));
router.use(users.routes(), users.allowedMethods())
router.use(echarts.routes(), echarts.allowedMethods())
router.use(menu.routes(), menu.allowedMethods())
router.use(role.routes(), role.allowedMethods())
router.use(dept.routes(), dept.allowedMethods())
router.use(leave.routes(), leave.allowedMethods())
router.use(uploads.routes(), uploads.allowedMethods())
app.use(router.routes(), router.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

const cors = require('koa2-cors') // 使用 koa2-cors 而不是 cors
// CORS 配置应该在其他中间件之前
app.use(cors({
  origin: '*', // 开发环境下可以设置为 *，生产环境应设置具体域名
  credentials: true,
  allowMethods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowHeaders: ['Content-Type', 'Authorization']
}))

module.exports = app
